package com.yisu.expressway.manager.core.service.impl;

import com.google.common.collect.Lists;
import com.yisu.expressway.ewf.entity.GoodsCategory;
import com.yisu.expressway.manager.core.mapper.GoodsCategoryMapper;
import com.yisu.expressway.manager.core.service.IGoodsCategory;
import com.yisu.expressway.manager.domain.request.GoodsCategoryRequest;
import com.yisu.expressway.manager.domain.util.CacheManager;
import com.yisu.expressway.manager.domain.vo.Cache;
import org.apache.calcite.linq4j.Linq4j;
import org.apache.calcite.linq4j.function.Predicate1;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by xlt on 2017/4/21.
 */
@Service
public class GoodsCategoryImpl implements IGoodsCategory {
    @Resource
    private GoodsCategoryMapper goodsCategoryMapper;
    private static StringBuilder jsonBuilder = new StringBuilder();
    private static List<GoodsCategory> goodsCategoryList;

    /**
     * 编辑商品类目信息
     *
     * @param goodsCategory 商品类目基本信息
     * @return 成功，失败
     */
    @Override
    public boolean modifyGoodsCategory(GoodsCategory goodsCategory) {
        try {
            GoodsCategory entity = goodsCategoryMapper.selectByPrimaryKey(goodsCategory.getId());
            if (entity == null) {
                goodsCategoryMapper.insert(goodsCategory);
            } else {
                goodsCategoryMapper.updateByPrimaryKey(goodsCategory);
            }
            CacheManager.clearAll();
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return false;
    }

    /**
     * 通过主键ID获取商品类目信息
     *
     * @param primaryKey 主键信息
     * @return 商品类目信息
     */
    @Override
    public GoodsCategory getGoodsCategoryModelByPrimaryKey(long primaryKey) {
        return goodsCategoryMapper.selectByPrimaryKey(primaryKey);
    }

    /**
     * 通过主键删除商品类目信息
     *
     * @param primaryKey 主键信息
     * @return 成功失败
     */
    @Override
    public boolean deleteGoodsCategory(long primaryKey) {
        /**
         * 如果商品类目下存在商品，则不允许删除商品类目
         */
        CacheManager.clearAll();
        return goodsCategoryMapper.deleteByPrimaryKey(primaryKey) > 0;
    }

    /**
     * 通过节点ID，获取商品类目树结构信息
     *
     * @param nodeId 节点ID
     * @return 树信息
     */
    @Override
    public String getGoodsCategoryTreeInfo(String nodeId) {
        try {
            String id = "0"; //当前要开始展开的节点
            String pid = ""; //父节点
            String name = "商品类目";
            Integer level = 0;
            jsonBuilder = new StringBuilder();
            jsonBuilder.append("[");
            if (StringUtils.isEmpty(nodeId)) {
                return jsonBuilder.toString();
            }
            if (nodeId.equals("0")) {
                goodsCategoryList = goodsCategoryMapper.getChildDataByParentId(nodeId);
                if (CollectionUtils.isEmpty(goodsCategoryList)) {
                    jsonBuilder.append("{id:'" + id + "', pId:'" + pid + "', name:'" + name + "',categoryCode:'" + id + "',open:true, iconSkin:'folder'}");
                } else {
                    jsonBuilder.append("{id:'" + id + "', pId:'" + pid + "', name:'" + name + "',categoryCode:'" + id + "',open:true, isParent: true, iconSkin:'folder'}");
                }
            }
            addGoodsCategoryTreeChildNodeInfo(nodeId, level);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        jsonBuilder.append("]");
        return jsonBuilder.toString();
    }

    /**
     * 通过节点ID，获取商品类目一级树结构信息
     *
     * @return 树信息
     */
    @Override
    public String getGoodsCategoryTreeInfoForFirstLevel() {
        try {
            String id = "0"; //当前要开始展开的节点
            String pid = ""; //父节点
            String name = "商品类目";
            jsonBuilder = new StringBuilder();
            jsonBuilder.append("[");
            goodsCategoryList = goodsCategoryMapper.getChildDataByParentId(String.valueOf(0));
            if (CollectionUtils.isEmpty(goodsCategoryList)) {
                jsonBuilder.append("{id:'" + id + "', pId:'" + pid + "', name:'" + name + "',categoryCode:'" + id + "',open:true, iconSkin:'folder'}");
            } else {
                jsonBuilder.append("{id:'" + id + "', pId:'" + pid + "', name:'" + name + "',categoryCode:'" + id + "',open:true, isParent: true, iconSkin:'folder'}");
                for (GoodsCategory item : goodsCategoryList) {
                    if (!jsonBuilder.toString().equals("["))
                        jsonBuilder.append(",");
                    List<GoodsCategory> categoryList = goodsCategoryMapper.getChildDataByParentId(String.valueOf(item.getId()));
                    if (!CollectionUtils.isEmpty(categoryList)) {
                        jsonBuilder.append("{id:'" + item.getId() + "', pId:'0', name:'" + item.getCategoryName() + "',categoryCode:'" + item.getCategoryCode() + "',open:true, isParent: false, iconSkin:'folder'}");
                    } else {
                        jsonBuilder.append("{id:'" + item.getId() + "', pId:'0', name:'" + item.getCategoryName() + "',categoryCode:'" + item.getCategoryCode() + "',open:true, iconSkin:'folder'}");
                    }
                }
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        jsonBuilder.append("]");
        return jsonBuilder.toString();
    }

    /**
     * 通过父节点ID获取下级最大排序
     *
     * @param parentId 父节点信息
     * @return 排序值
     */
    @Override
    public int getMaxSortByParentId(String parentId) {
        return goodsCategoryMapper.getMaxSortByParentId(parentId);
    }

    /**
     * 上移节点
     *
     * @param nodeId
     * @return
     */
    @Override
    public boolean moveUpByNodeId(String nodeId) {
        try {
            final GoodsCategory entity = goodsCategoryMapper.selectByPrimaryKey(Long.parseLong(nodeId));
            if (entity != null) {
                //获取同级下所有节点
                List<GoodsCategory> goodsCategories = goodsCategoryMapper.getChildDataByParentId(entity.getParentCode());
                if (!CollectionUtils.isEmpty(goodsCategories)) {
                    GoodsCategory element = Linq4j.asEnumerable(goodsCategories).first(new Predicate1<GoodsCategory>() {
                        @Override
                        public boolean apply(GoodsCategory goodsCategory) {
                            return (goodsCategory.getId() + "").equals(entity.getId() + "");
                        }
                    });
                    if (element != null) {
                        int element_index = goodsCategories.indexOf(element);
                        if (element_index != 0) {
                            //前一元素信息
                            GoodsCategory upElement = goodsCategories.get(element_index - 1);
                            //更改当前元素下标排序
                            GoodsCategory updateModel = new GoodsCategory();
                            updateModel.setId(element.getId());
                            updateModel.setSort(upElement.getSort());
                            goodsCategoryMapper.updateSort(updateModel);
                            //更改前一元素下标排序
                            updateModel = new GoodsCategory();
                            updateModel.setId(upElement.getId());
                            updateModel.setSort(element.getSort());
                            goodsCategoryMapper.updateSort(updateModel);
                            CacheManager.clearAll();
                            return true;
                        }
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return false;
    }

    /**
     * 下移节点
     *
     * @param nodeId
     * @return
     */
    @Override
    public boolean moveDownNodeId(String nodeId) {
        try {
            final GoodsCategory currentEntity = goodsCategoryMapper.selectByPrimaryKey(Long.parseLong(nodeId));
            if (currentEntity != null) {
                //获取同级下所有节点
                List<GoodsCategory> goodsCategories = goodsCategoryMapper.getChildDataByParentId(currentEntity.getParentCode());
                if (!CollectionUtils.isEmpty(goodsCategories)) {
                    GoodsCategory currentElement = Linq4j.asEnumerable(goodsCategories).first(new Predicate1<GoodsCategory>() {
                        @Override
                        public boolean apply(GoodsCategory goodsCategory) {
                            return (goodsCategory.getId() + "").equals(currentEntity.getId() + "");
                        }
                    });
                    if (currentElement != null) {
                        int element_index = goodsCategories.indexOf(currentElement);
                        if (element_index != goodsCategories.size()) {
                            GoodsCategory upElement = goodsCategories.get(element_index + 1);
                            GoodsCategory updateModel = new GoodsCategory();
                            //更改前一元素下标排序
                            updateModel = new GoodsCategory();
                            updateModel.setId(upElement.getId());
                            updateModel.setSort(currentElement.getSort());
                            goodsCategoryMapper.updateSort(updateModel);
                            //更改当前元素下标排序
                            updateModel.setId(currentElement.getId());
                            updateModel.setSort(upElement.getSort());
                            goodsCategoryMapper.updateSort(updateModel);
                            CacheManager.clearAll();
                            return true;
                        }
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return false;
    }

    /**
     * 通过节点ID，获取当前节点下是否存在子集节点
     *
     * @param nodeId 当前节点
     * @return 是、否
     */
    @Override
    public boolean isHaveChildNode(String nodeId) {
        return goodsCategoryMapper.isHaveChildNode(nodeId) > 0;
    }

    /**
     * 通过商品分类编号获取其路径名称
     *
     * @param goodsCategoryCode
     * @return
     */
    @Override
    public String getGoodsCategoryPathNameByGoodsCategoryCode(String goodsCategoryCode) {
        GoodsCategory entity = goodsCategoryMapper.getGoodsCategoryByGoodsCategoryCode(goodsCategoryCode);
        if (entity != null) {
            List<String> pathNodeCodes = Linq4j.asEnumerable(org.apache.commons.lang3.StringUtils.split(entity.getNodePath(), ",，")).toList();
            List<GoodsCategory> goodsCategories = goodsCategoryMapper.getGoodsCategoryListByGoodsCategoryCodes(pathNodeCodes);
            List<String> pathName = Lists.newArrayList();
            if (!CollectionUtils.isEmpty(goodsCategories)) {
                for (GoodsCategory goodsCategory : goodsCategories) {
                    pathName.add(goodsCategory.getCategoryName());
                }
            }
            if (pathName != null && pathName.size() > 0) {
                return org.apache.commons.lang3.StringUtils.join(pathName, ">>");
            }
        }
        return "";
    }

    /**
     * 充值商品分类
     *
     * @return
     */
    @Override
    public boolean resetGoodsCategory() {
        CacheManager.clearAll();
        return goodsCategoryMapper.resetGoodsCategory();
    }

    /**
     * 通过类目名称获取类目对象信息--解析数据专用
     *
     * @param categoryName 类目名称
     * @return
     */
    @Override
    public GoodsCategory getGoodsCategoryModelByName(String categoryName) {
        return goodsCategoryMapper.getGoodsCategoryModelByName(categoryName);
    }

    /**
     * 通过类目名称及上级编号获取类目对象信息--解析数据专用
     *
     * @param goodsCategoryRequest 请求参数
     * @return
     */
    @Override
    public GoodsCategory getGoodsCategoryModelByNameAndParentId(GoodsCategoryRequest goodsCategoryRequest) {
        return goodsCategoryMapper.getGoodsCategoryModelByNameAndParentId(goodsCategoryRequest);
    }


    protected void addGoodsCategoryTreeChildNodeInfo(String nodeId, Integer level) {
        goodsCategoryList = goodsCategoryMapper.getChildDataByParentId(nodeId);
        if (!CollectionUtils.isEmpty(goodsCategoryList)) {
            for (GoodsCategory item : goodsCategoryList) {
                if (!jsonBuilder.toString().equals("["))
                    jsonBuilder.append(",");
                Cache cache = CacheManager.getCacheInfo("GoodsCategory_" + item.getId());
                List<GoodsCategory> categoryList = goodsCategoryMapper.getChildDataByParentId(String.valueOf(item.getId()));
                level += 1;
                String openStatus = "true";
                if (level > 2)
                    openStatus = "false";
                if (!CollectionUtils.isEmpty(categoryList)) {
                    jsonBuilder.append("{id:'" + item.getId() + "', pId:'" + nodeId + "', name:'" + item.getCategoryName() + "',categoryCode:'" + item.getCategoryCode() + "',open:'" + openStatus + "', isParent: true, iconSkin:'folder'}");
                } else {
                    jsonBuilder.append("{id:'" + item.getId() + "', pId:'" + nodeId + "', name:'" + item.getCategoryName() + "',categoryCode:'" + item.getCategoryCode() + "',open:'" + openStatus + "', iconSkin:'folder'}");
                }

                addGoodsCategoryTreeChildNodeInfo(String.valueOf(item.getId()), level);
            }
        }
    }
}
